<template>
        <uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'slide-left']" :show="isShowCallType">
            <!-- <u-sticky offset-top="200"> -->
            <view v-show="isShowCallType" class="action-buttons" id="action-buttons">
                <u-button type="warning" :disabled="callStatus == 1" style="float:left;height:60rpx;width:100rpx;margin-right:20rpx;" text="回拨" @click="handleDetailByCust('back')">回拨</u-button>
                <u-button type="primary"  :disabled="callStatus == 1" style="float:left;height:60rpx;width:100rpx;margin-right:20rpx;" text="外呼" @click="handleDetailByCust('call')">外呼</u-button>
                <u-button type="primary" style="float:left;height:60rpx;width:100rpx;" text="SIP外呼" :disabled="(isSip == 0 || isSip == '0' || callStatus == 1) ? true:false" @click="handleDetailByCust('sip')" >SIP</u-button>
                
                <!-- <u-button type="error" style="float:left;height:60rpx;width:100rpx;margin-left:20rpx;" :disabled="callStatus == 0" text="挂断通话" @click="handleEndCall()" >挂断</u-button> -->
                
                <view style="position: absolute;width:160rpx;height:40rpx;background-color: orangered;border-radius: 20rpx;text-align: center;font-size:30rpx;line-height: 40rpx;color:#fff;margin-left:200rpx;margin-top:-45rpx;" v-show="(isSip == 0 || isSip == '0') ? true:false">SIP未注册</view>
            </view>
        
            
            <!-- </u-sticky> -->
            
            <u-toast ref="uToastsCallType" />
			
			<u-modal v-model="isCalls" :show-cancel-button="true" :title-style="{fontSize:'40rpx'}" confirm-text="去开启" :show-title="false" title="未开启通话自动录音功能无法卡外呼" @cancel="isCalls = false" @confirm="confirmOpenVoice">
                <text style="font-size:38rpx;font-weight: bold;display: block;width:98%;padding-left:1%;line-height:45rpx;margin-top:20rpx;">未开启通话自动录音功能无法卡外呼</text>
			    <view class="slot-content" style="height:400rpx;">
			        <text>请自动开启通话录音功能,否则无法进行外呼并生成通话录音。以下为开启方法:</text>
			        <text>1.在手机自带拨号盘通话设置中,开启'通话自动录音'</text>
			        <text>2.在系统设置中,搜索'自动录音'或'通话设置',开启'通话自动录音'</text>
			    </view>
			</u-modal>
			
			<view v-show="isShowSim" class="sim_view" >
				<view class="sim_item" @click="handleChangeSim(1)"><u-icon name="phone" color="#585858" size="28"></u-icon> 卡1</view>
				<view class="sim_item" @click="handleChangeSim(2)"><u-icon name="phone" color="#585858" size="28"></u-icon> 卡2</view>
				<view class="sim_btn" @click="handleCloseSelSim">取消</view>
			</view>
        </uni-transition>
</template>

<script>
	import {
		getOrderGroup,
	    getClickToDial,
	    changeCallNumStatus
	} from "@/api/task.js";
    
    import {
    	isBlackByNumber
    } from "@/api/index.js";
	
	import {
		mapGetters,mapState
	} from "vuex";
    
    import {getTime} from "@/utils/data.js";
    
    // import websip from "@/pages/index/websip.vue"; //WEBSIP应用
	
	const callModule = uni.requireNativePlugin("leven-call-CallModule");
    
    let that;
	
    export default {
        data() {
            return {
                isCompanyBlack:0,
                isBlack:0,
				isCalls:false,
				isCallsContext:'请先开启自动录音权限',
				isShowSim:false
                // currentCallType:''
            }
        },
        props:["isShowCallType","callData","callKey","callType"],
        // components:{websip},
		computed: {
			...mapGetters(["userInfo","isSip","taskType","isShowWebSip","sipPhone","callStatus","websipCallStatus","callingData","currentCallType"]),
			...mapState({
		        isSip:state => state.task.isSip,
                isShowWebSip:state=>state.task.isShowWebSip,
                sipPhone:state=>state.task.sipPhone,
                callStatus:state=>state.task.callStatus,
                websipCallStatus:state=>state.task.websipCallStatus,
				callingData: state=>state.task.callingData,
				currentCallType:state=>state.task.currentCallType
			})
		},
		watch:{
			isSip(newVal, oldVal) {
				// 监听文本框值的改变
				console.log("isSip watch newVal",newVal);
				console.log("isSip watch oldVal",oldVal);
			},
            
            isShowCallType(newVal, oldVal) {
            	// 监听文本框值的改变
            	console.log("isShowCallType watch newVal",newVal);
            	console.log("isShowCallType watch oldVal",oldVal);
            }
		},

        methods: {
			//开启自动通话录音
			confirmOpenVoice() {
				callModule.toCallAutoRecorderPage(res => {
					console.log("开启通话自动录音",res);
					
					this.$console.info("开启通话自动录音",res);
				});
			},
			
            //挂断通话
            handleEndCall(){
			
                callModule.endCall(res => {
                    console.log("endCall",res);
                    console.log("currentCallType",this.currentCallType);
                  
                    this.$store.dispatch("setCallStatus",0);
					this.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
                  
                    if(this.currentCallType == 'sip'){
                        //通知SIP  挂断通话
                        // websip.methods.handleSendMessage('hangup',{});
                      
                        this.$store.dispatch("setWebsipCallStatus","hangup");
                    }
                });
            },
            
			//根据客户数据处理
			handleDetailByCust(type){
				let params = this.callData;
				let that = this;
				
                params.phone = this.callType == "index" ? params.unum : params.num;
				
				console.log("params:",params);
                
                // this.currentCallType = type;
				// this.$store.dispatch("setCurrentCallType",type);
                
                if(params.unum == ""){
                	this.$refs.uToastsCallType.show({
                		title: "请输入号码！",
                		type: 'error',
                		duration: '2000',
                	});
                    
                    return false;
                }
                
                if(type == 'back'){
                    if(this.userInfo.shownum == "" || this.userInfo.shownum == '0'){
                        this.$refs.uToastsCallType.show({
                        	title: "请设置外呼主叫号码",
                        	type: 'error',
                        	duration: '3000',
                        });
                        
                        return false;
                    }
                }
				
				//获取客户信息
				isBlackByNumber({
					'cid': this.userInfo.companyid,
					'num': params.phone,
					'token':this.userInfo.token,
					'seat':this.userInfo.seat
				}).then(res=>{
				    console.log("getCustomerInfoByTidGroup res",res);
			        this.$console.info("getCustomerInfoByTidGroup res",res);
				    // taskCallData.value = res.data;
				    let data = res.data.data;
				
				    if(data != null){
						
						//判断是否为开启黑名单
						if(data.is_black >= 1){
						    // let title_str = (data.is_black == 1) ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':'已开启黑名单过滤，该号码为企业黑名单，禁止外呼！';
                            
                            let title_str = data.is_black == 1 ? '已开启黑名单过滤，该号码为第三方黑名单，禁止外呼！':(data.is_black == 2 ? '已开启黑名单过滤，该号码为企业黑名单，禁止外呼！':'已开启黑名单过滤，该号码为系统黑名单，禁止外呼！');
						    
						    this.$refs.uToastsCallType.show({
						    	title: title_str,
						    	type: 'error',
						    	duration: '1000',
						    });
							
							that.$store.dispatch("setCallStatus",0);
							that.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
							
							that.$store.dispatch("setCurrentCallType","");
							
						    return false;
						}else{
							this.$store.dispatch("setCurrentCallType",type);
							
                            if(type == "back"){
                                //回拨
                                this.handleCallBack(params);
                            }else if(type == 'call'){
                                //外呼
								console.log("call  ",data.is_call);
								if(data.is_call == 1){
									callModule.checkCallAutoRecorder(res_module => {
										console.log("检测通话录音权限 结果",res_module);
										
										that.$console.info("检测通话录音权限 结果",res_module);
										
										if(!res_module.data.isOpen){
											console.log("未开启自动通话录音");
											
											that.$console.info("未开启自动通话录音");
											
											//提示，没有开启自动通话录音
											that.isCalls = true;
											
										}else{
											that.isCalls = false;
											this.handleCallPhone(params);
										}
									});
								}else{
                                    //直接卡外呼
									this.handleCallPhone(params);
                                    
                                    
                                    //测试  
                                    // callModule.isMultiSim(res => {
                                    //   console.log("handlcallphone ismultisim:",res);
                                    // });
                                    
								}
								
								console.log("call  ",data.is_call,that.isCalls);
								
								// if(this.isCalls == false){
								// 	//this.handleCallPhone(params);
								// }

                            }else if(type == 'sip'){
                                //SIP
                                this.handleCallSip(params);
                            }
                        }
				    }else{
                        //未取到号码信息
                        this.$refs.uToastsCallType.show({
                        	title: "未获取到号码信息",
                        	type: 'error',
                        	duration: '1000',
                        });
                        return false;
                    }
				});
			
                //关闭
                // this.$emit("closeShowCallType","");
			},
			
            //回拨
            handleCallBack(data){

                //调用接口
                let params = {
                    'company_id':this.userInfo.companyid,
                    'caller':this.userInfo.seat,
                    'callee':data.phone,
                    'seat':this.userInfo.seat,
                    'type':5,
                    'pid':this.userInfo.pid,
                    'shownum': this.userInfo.shownum,
                    'phone': data.phone,
                    'cid': this.userInfo.companyid,
					'id':data.id
                }
                
                console.log("callorder params",params);
            
                console.info("快速回拨--参数",params);
                this.$console.info("快速回拨--参数",params);
                
                console.info("快速回拨--先停止定时任务 ",params.callee);
                this.$console.info("快速回拨--先停止定时任务 ",params.callee);
                
                //先清除任务
                clearInterval(this.$globalData.taskTimer);
                this.$globalData.taskTimer = null;
                
                //先调用回拨接口，有返回结果后保存通话记录
                getClickToDial(params).then(res => {
                    console.log("getClickToDial res", res);
                    this.$console.info("快速回拨--回拨接口成功 返回数据",res);
                    
                    if(res.data.code == 200){
                        this.$refs.uToastsCallType.show({
                            title: "回拨成功",
                            type: 'success',
                            duration: '2000',
                        });
                        
                        //设置通话状态为通话中
      //                   this.$store.dispatch("setCallStatus",1);
						// this.$store.dispatch("setCallingData",{id:data.id,phone:params.callee,type:this.callType});
                        
                        //通话状态监听
                        params.start_time = new Date().getTime();
                                                    
                        //放入全局参数
                        // this.$globalData.callData = params;
                        
                        //记录日志
                        console.info("快速回拨--开始外呼 ", params.callee);
                        this.$console.info("快速回拨--开始外呼 ",params.callee);

                    }else{
                        this.$refs.uToastsCallType.show({
                            title: res.data.msg,
                            type: 'error',
                            duration: '3000',
                        });
                        
                        console.info("快速回拨--回拨接口失败 返回数据 ", params.callee);
                        this.$console.info("快速回拨--回拨接口失败 返回数据 ", params.callee);
                        
                        //开启任务定时器
                        if(this.taskType == 0 && this.$globalData.taskTimer == null){
                            this.$globalData.taskTimer = setInterval(()=>{
                                uni.$emit("handleGetCall");
                            },2000);
                        }
                    }
                }).catch(err => {
                    console.info("快速回拨--回拨接口错误 返回数据 err", params.callee,err);
                    this.$console.info("快速回拨--回拨接口错误 返回数据 ", params.callee,err);
					
					this.$refs.uToastsCallType.show({
					    title: "回拨接口错误",
					    type: 'error',
					    duration: '3000',
					});
                    
                    //开启任务定时器
                    if(this.taskType == 0 && this.$globalData.taskTimer == null){
                        this.$globalData.taskTimer = setInterval(()=>{
                            uni.$emit("handleGetCall");
                        },2000);
                    }
                });

            },
            
            //SIP
            handleCallSip(data){
                this.$console.info("快速外呼--SIP外呼 ", data);
                
                //设置通话状态为通话中
                this.$store.dispatch("setCallStatus",1);
				
				this.$store.dispatch("setCallingData",{id:data.id,phone:data.phone,type:this.callType});
                
                // this.$store.dispatch("setPageCur","websip");
                
                this.$store.dispatch("setSipPhone",data.phone);
                this.$store.dispatch("setIsShowWebSip",1);
            },
			
			//取消双卡选择
			handleCloseSelSim(){
				this.isShowSim = false;
				
				//设置通话状态为通话中
				this.$store.dispatch("setCallStatus",0);
				
				this.$store.dispatch("setCallingData",{});
				
				//开启任务定时器
				if(this.taskType == 0 && this.$globalData.taskTimer == null){
				    this.$globalData.taskTimer = setInterval(()=>{
				        uni.$emit("handleGetCall");
				    },2000);
				}
			},
			
			//双卡选择那个卡呼
			handleChangeSim(sim){
				let _this = this;
				let phone = this.callType == "index" ? this.callData.unum : this.callData.num;
				
				//启动通话状态监听
				if(_this.$globalData.callStatusTimer == null){
					console.log("calltype  通话状态监听");
					_this.$globalData.callStatusTimer = setInterval(()=>{
						uni.$emit("handleRegisterListener");
					},500);
				}
				
				//自动拨号
				callModule.callPhone({
					// 拨打号码
					number: phone,
					// 卡槽索引，1.卡槽1(默认),2.卡槽2
					slot: sim,
					//是否是座机
					isTelephone: false
				}, res => {
					console.log("callphone",res);
				});
			},
            
            //拨打电话外呼
            handleCallPhone(data){
            	let _this = this;
            	
            	console.log("handlecallphone callData:",_this.callData,data);
                
                //设置通话状态为通话中
                this.$store.dispatch("setCallStatus",1);
				
				this.$store.dispatch("setCallingData",{id:data.id,phone:data.phone,type:this.callType});
                
                //调用接口
                let params = {
                    'company_id':_this.userInfo.companyid,
                    'caller':_this.userInfo.seat,
                    'callee':data.phone,
                    'seat':_this.userInfo.seat,
                    'type':3,
                    'pid':data.pid,
                    'tid':data.tid
                }
                
                console.log("callorder params",params,_this.callData);
                _this.$console.info("快速外呼--外呼参数 ",params);
                
                //修改任务列表的号码状态
                _this.$emit("changeNumStatus",{...params,status:1,num:params.callee});
                
                console.info("快速外呼--先停止定时任务 ",params.callee);
                _this.$console.info("快速外呼--先停止定时任务 ", params.callee);
                
                //先清除任务
                clearInterval(_this.$globalData.taskTimer);
                _this.$globalData.taskTimer = null;
                
                //获取录音目录
                plus.io.requestFileSystem(
                    plus.io.PRIVATE_DOC, // 私有文档目录（对应 _doc 路径）
                    (fs) => {
                      // 定义目录路径（示例：在 _doc 下创建 myFolder）
                      let dirPath = 'logs';
                            
                      // 检查并创建目录
                      fs.root.getDirectory(
                        dirPath,
                        { create: true }, // 自动创建目录
                        (entry) => {
                            console.log('快速外呼--创建文件夹成功:',entry.fullPath);
                            _this.$console.info('快速外呼--创建文件夹成功:',entry.fullPath);
                            uni.setStorageSync("record_files",entry.fullPath);
                }, function(e) {
                        console.log('快速外呼--创建文件夹失败:',e.message);
                        _this.$console.info('快速外呼--创建文件夹失败:',e.message);
                    });
                }, function(e) {                    
                    console.log('快速外呼--请求文件系统失败:',e.message);
                    _this.$console.info('快速外呼--请求文件系统失败:',e.message);
                });
    
                //提前修改号码状态
                // changeCallNumStatus(params).then(res=>{
                    //通话状态监听
                    // params.start_time = new Date().getTime();
                    
                    params.start_time = getTime();
                    
                    console.info("快速外呼--接口修改号码状态 成功", params.callee);
                    _this.$console.info("快速外呼--接口修改号码状态 成功",params.callee);
                    
                    //记录日志
                    console.info("快速外呼--开始外呼 ",params.callee);
                    _this.$console.info("快速外呼--开始外呼 ",params.callee);
                    
                    //放入全局参数
                    // _this.$globalData.callData = params;
                    
                    // TODO 添加到全局缓存中
                    _this.$globalData.callData.push(params);
					
					// callModule.isMultiSim(res => {
					// 	console.log("isMultiSim",res);
					  
					// 	if(res.data.isMultiSim){
					// 		//是双卡
					// 		_this.isShowSim = true;
					// 	}else{
					// 		//启动通话状态监听
					// 		if(_this.$globalData.callStatusTimer == null){
					// 			console.log("calltype  通话状态监听");
					// 			_this.$globalData.callStatusTimer = setInterval(()=>{
					// 				uni.$emit("handleRegisterListener");
					// 			},500);
					// 		}
							
					// 		//自动拨号
					// 		plus.device.dial(params.callee,false);
					// 	}
					// });
					

                
                    //自动拨号
                    plus.device.dial(params.callee,false);
					
					//启动通话状态监听
					if(_this.$globalData.callStatusTimer == null){
						console.log("calltype  通话状态监听");
						_this.$globalData.callStatusTimer = setInterval(()=>{
							uni.$emit("handleRegisterListener");
						},500);
					}
                    
                    console.log('外呼，完成');
                    _this.$console.info("快速外呼--转到手机系统外呼 ",params);
     //            }).catch(err=>{
     //                console.info("快速外呼--接口修改号码状态 失败 err"+params.callee,err);
     //                _this.$console.info("快速外呼--接口修改号码状态 失败 err "+params.callee,err);
					
					// //设置通话状态为通话中
					// this.$store.dispatch("setCallStatus",0);
					
					// this.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
                    
     //                //开启任务定时器
     //                if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
     //                    _this.$globalData.taskTimer = setInterval(()=>{
     //                        uni.$emit("handleGetCall");
     //                    },2000);
     //                }
     //            });
            
            
            }
            
        }
    }
</script>

<style scoped>
    .action-buttons {
          position: absolute;
          margin-left: 100rpx;
          margin-top:25rpx;
          float:left;
          background: #fff;
          padding:16rpx 10rpx;
          border: 2rpx solid #ddd;
          border-radius: 28rpx;
          box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
          z-index: 1000;
          width:auto;
    }
    
    .action-item {
      padding: 15rpx 26rpx;
      border-bottom: 2rpx solid #eee;
      white-space: nowrap;
      /* background-color:#cff4f9; */
      float:left;
      font-weight: bold;
      font-size:32rpx;
      border-radius: 20rpx;
      margin:0rpx 10rpx;
    }
    
    .action-item:last-child {
      border-bottom: none;
    }
    
    .orange{
        background-color: #ffeecb;
    }
    
    .blue{
        background-color: #d4eeff;
    }
    
    .sip{
        background-color: orangered;
        color:#fff;
    }
	
	.sim_view{
		width:90%;height:165px;margin-left:5%;
		border-radius: 15px;
		position: fixed;z-index:100000000000;bottom:15px;background-color: #f3f3f3;border:#e5e5e5 1px solid;
		box-shadow: 0 0 blur 10px rgba(173, 173, 173, 0.2);
		padding-top:15px;
	}
	
	.sim_item{
		width:80%;
		float:left;
		margin-left:10%;
		clear:both;
		margin-bottom:10px;
		
		border-radius: 20px;
		border:#ececec 1px solid;
		background-color: #fff;
		height:40px;
		
		font-size:16px;
		text-align: center;
		line-height: 40px;
	}
	
	.sim_btn{
		width:80%;
		float:left;
		margin-left:10%;
		clear:both;
		margin-bottom:10px;
		
		border-radius: 20px;
		/* border:#ececec 1px solid; */
		height:40px;
		
		font-size:16px;
		text-align: center;
		line-height: 40px;
	}
</style>
